package com.ruoyi.ex.service.impl;

import java.util.*;
import java.util.concurrent.TimeUnit;

import com.doudou.core.container.ListUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.value.Values;
import com.ruoyi.ex.service.ExService;
import com.ruoyi.ex.service.IExQuestionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.ex.mapper.ExTestBankMapper;
import com.ruoyi.ex.domain.ExTestBank;
import com.ruoyi.ex.service.IExTestBankService;

/**
 * 自测题库Service业务层处理
 *
 * @author zzx
 * @date 2023-03-25
 */
@Service
public class ExTestBankServiceImpl implements IExTestBankService {
    @Autowired private ExTestBankMapper exTestBankMapper;
    @Autowired private IExQuestionService exQuestionService;

    @Autowired private RedisCache redisCache;
    @Autowired private ExService exService;

    /**
     * 查询自测题库
     *
     * @param id 自测题库主键
     * @return 自测题库
     */
    @Override
    public ExTestBank selectExTestBankById(Long id) {
        ExTestBank exTestBank = exTestBankMapper.selectExTestBankById(id);
        if(ObjectUtil.isNotEmpty(exTestBank) && exTestBank.getStatus().equals(1)){//答题结束
            Map<Long, Boolean> questionAnswers = new HashMap<>();
            //格式化已回答列表
            JSONArray questionIdList = exTestBank.getQuestionIdList();
            Map<Long, Object> answerMap = exService.rightTotal(exTestBank.getAnswerMap(),exTestBank.getQuestionIds());
            for (int i = 0; i < questionIdList.size(); i++) {
                long qid = questionIdList.getLong(i);
                questionAnswers.put(qid,answerMap.containsKey(qid));
            }
            exTestBank.setQuestionAnswers(questionAnswers);
        }
        return exTestBank;
    }

    /**
     * 查询自测题库列表
     *
     * @param exTestBank 自测题库
     * @return 自测题库
     */
    @Override
    public List<ExTestBank> selectExTestBankList(ExTestBank exTestBank) {
        return exTestBankMapper.selectExTestBankList(exTestBank);
    }

    /**
     * 新增自测题库
     *
     * @param exTestBank 自测题库
     * @return 结果
     */
    @Override
    public int insertExTestBank(ExTestBank exTestBank) {
                exTestBank.setCreateTime(DateUtils.getNowDate());
            return exTestBankMapper.insertExTestBank(exTestBank);
    }

    /**
     * 修改自测题库
     *
     * @param exTestBank 自测题库
     * @return 结果
     */
    @Override
    public int updateExTestBank(ExTestBank exTestBank) {
        ExTestBank exTestBank1 = exTestBankMapper.selectExTestBankById(exTestBank.getId());
        //计算分数
        Map<Long, Object> answerMap = exService.rightTotal(exTestBank.getAnswerMap(),exTestBank1.getQuestionIds());
        exTestBank.setAnswerList(JSONUtil.parseObj(exTestBank.getAnswerMap()).toString());
        exTestBank.setRight((long)answerMap.size());
        exTestBank.setStatus(1);
        exTestBank.setScore(NumberUtil.round((double) exTestBank.getRight() / exTestBank.getTotal() * 100,2).doubleValue());
        exTestBank.setEndTime(new Date());
        return exTestBankMapper.updateExTestBank(exTestBank);
    }

    /**
     * 批量删除自测题库
     *
     * @param ids 需要删除的自测题库主键
     * @return 结果
     */
    @Override
    public int deleteExTestBankByIds(Long[] ids) {
        return exTestBankMapper.deleteExTestBankByIds(ids);
    }

    /**
     * 删除自测题库信息
     *
     * @param id 自测题库主键
     * @return 结果
     */
    @Override
    public int deleteExTestBankById(Long id) {
        return exTestBankMapper.deleteExTestBankById(id);
    }

    @Override
    public void saveAnswers(Long userId,Long bankId, JSONObject answers) throws Exception {
        //组装key
        String key = StrUtil.format(Values.EX_TEST_DOING_ANSWER_KEY,new HashMap<String,Object>(){{
            put("userId",userId);put("bandId",bankId);
        }});
        redisCache.setCacheObject(key,answers,1, TimeUnit.DAYS);
    }

    @Override
    public JSONObject getAnswers(Long userId,Long bankId) {
        //组装key
        String key = StrUtil.format(Values.EX_TEST_DOING_ANSWER_KEY,new HashMap<String,Object>(){{
            put("userId",userId);put("bandId",bankId);
        }});
        Object cacheObject = redisCache.getCacheObject(key);
        return ObjectUtil.isNotEmpty(cacheObject) ? JSONUtil.parseObj(cacheObject) : new JSONObject();
    }
}
